﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
using System.Threading;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Http;

namespace NetCoreClass
{
    public class FtpUpDown
    {
        string ftpServerIP;

        string ftpUserID;

        string ftpPassword;
        private HttpContext _context;

        FtpWebRequest reqFTP;
        /// <summary>
        /// 服务器错误状态信息
        /// </summary>
        public string errormessage;

        public FtpUpDown(HttpContext context, string ftpServerIP, string ftpUserID, string ftpPassword)
        {
            _context = context;
            this.ftpServerIP = ftpServerIP;

            this.ftpUserID = ftpUserID;

            this.ftpPassword = ftpPassword;

        }
        public void Close()
        {
            reqFTP.Abort();
        }
        private void Connect(String path)//连接ftp
        {
                // 根据uri创建FtpWebRequest对象
            
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
           if (reqFTP != null)
            {
                // 指定数据传输类型
                reqFTP.UseBinary = true;
                // ftp用户名和密码
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            }
        }

        //都调用这个

        private string[] GetFileList(string path, string WRMethods)//上面的代码示例了如何从ftp服务器上获得文件列表
        {

            string[] downloadFiles;

            StringBuilder result = new StringBuilder();
            try
            {

                Connect(path);

                reqFTP.Method = WRMethods;

                WebResponse response = reqFTP.GetResponse();

                StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);//中文文件名

                string line = reader.ReadLine();

                while (line != null)
                {

                    result.Append(line);

                    result.Append("/n");

                    line = reader.ReadLine();

                }

                // to remove the trailing '/n' 
                if(result.Length>0 )
                result.Remove(result.ToString().LastIndexOf("/n"), 2);

                reader.Close();

                response.Close();

                return result.ToString().Split(new string[] { "/n" }, StringSplitOptions.None);

            }

            catch (Exception ex)
            {

                //System.Windows.Forms.MessageBox.Show(ex.Message);
                errormessage = ex.Message;
                downloadFiles = null;

                return downloadFiles;

            }

        }

        public string[] GetFileList(string path)//上面的代码示例了如何从ftp服务器上获得文件列表
        {

            return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectory);



        }



        public string[] GetFileList()//上面的代码示例了如何从ftp服务器上获得文件列表
        {

            return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectory);



        }
        /// <summary>  
        /// 获取目录和文件名,返回目录表。   
        /// </summary>    
        /// <param name="path">要获取的目录</param>      
        /// <returns></returns>      
        public string[,] GetCatalog_FileList(string path)
        {
            string[] fountainhead = GetFilesDetailList(path);
            if (fountainhead == null)
            {
                return null;
            }

            string[,] Catalog = new string[fountainhead.Length, 4];
            int dirCount = 0;
            for (int i = 0; i < fountainhead.Length; i++)
            {
                string d = fountainhead[i].Substring(0, 8);
                Regex re = new Regex("\\d\\d-\\d\\d-\\d\\d");
                if (re.IsMatch(d))
                {
                    Catalog[i, 0] += fountainhead[i].Substring(39, fountainhead[i].Length - 39);//FileName 
                    Catalog[i, 1] += fountainhead[i].Substring(30, 8);//FileSize   
                    Catalog[i, 2] += fountainhead[i].Substring(0, 17);//AmendDate            
                    Catalog[i, 3] += fountainhead[i].Substring(24, 5);
                    if (Catalog[i, 3] == "<DIR>")
                    {
                        dirCount++;
                    }
                }
                else
                {
                    if (fountainhead[i].Substring(0, 1) == "d")
                    {
                        Catalog[i, 3] = "<DIR>";
                        dirCount++;
                    }
                    else
                    {
                        Catalog[i, 3] = "";
                    }
                    int idxStart = fountainhead[i].LastIndexOf(" ");
                    //Catalog[i, 0] += fountainhead[i].Substring(56, fountainhead[i].Length - 56).Trim();//FileName 
                    Catalog[i, 0] += fountainhead[i].Substring(idxStart, fountainhead[i].Length - idxStart).Trim();//FileName 
                    Catalog[i, 1] += fountainhead[i].Substring(28, 15);//FileSize   
                    Catalog[i, 2] += fountainhead[i].Substring(42, 14);//AmendDate 

                }

            }
            string[,] fileList = new string[fountainhead.Length, 4];
            int dir = 0;
            for (int i = 0; i < fountainhead.Length; i++)
            {
                if (Catalog[i, 3] == "<DIR>")
                {
                    fileList[dir, 0] = Catalog[i, 0];
                    fileList[dir, 1] = Catalog[i, 1];
                    fileList[dir, 2] = Catalog[i, 2];
                    fileList[dir, 3] = Catalog[i, 3];
                    dir++;
                }
                else
                {
                    fileList[dirCount, 0] = Catalog[i, 0];
                    fileList[dirCount, 1] = Catalog[i, 1];
                    fileList[dirCount, 2] = Catalog[i, 2];
                    fileList[dirCount, 3] = Catalog[i, 3];
                    dirCount++;
                }
            }
            Catalog = null;
            return fileList;
        }
        public bool Upload(string filename, string path) //上面的代码实现了从ftp服务器上载文件的功能
        {

            FileInfo fileInf = new FileInfo(filename);
            string uri = "ftp://" + ftpServerIP + "/" + path + "/" + fileInf.Name;
            if (path == "")
            {
                uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
            }
            else if (path.IndexOf("/") == 0)
            {
                //string p = path.Substring(0, 1);
                //string path1 = "";
                //if (p == "/")
                //{
                //    path1 = path.Substring(1);
                //    uri = "ftp://" + ftpServerIP + "//" + path1 + "/" + fileInf.Name;
                //}
                //else
                //{
                    uri = "ftp://" + ftpServerIP + "/" + path + "/" + fileInf.Name;
                //}
                   

            }
            // 默认为true，连接不会被关闭

            // 在一个命令之后被执行


            Connect(uri);//连接          
            reqFTP.KeepAlive = false;
            reqFTP.UsePassive = true;
            reqFTP.ReadWriteTimeout = 10000;
            // 指定执行什么命令

            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            // 上传文件时通知服务器文件的大小

            reqFTP.ContentLength = fileInf.Length;
            // 缓冲大小设置为kb 

            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            long FileSize = fileInf.Length;
            // 打开一个文件流(System.IO.FileStream) 去读上传的文件

            FileStream fs = fileInf.OpenRead();
            try
            {

                // 把上传的文件写入流
                // Thread.Sleep(10 * 1000);
                Stream strm = reqFTP.GetRequestStream();
                while (true)
                {
                    // 每次读文件流的kb 
                    int contentLen = fs.Read(buff, 0, buffLength);
                    // 把内容从file stream 写入upload stream 
                    if (contentLen == 0)
                    {
                        break;
                    }
                    strm.Write(buff, 0, contentLen);
                }
                // 关闭两个流
                strm.Close();
                fs.Close();
                errormessage = uri;
                return true;
            }

            catch (Exception ex)
            {
                errormessage = ex.Message;
                fs.Close();
                return false;
            }
        }
        public void Upload(string filename, string path, string progress) //上面的代码实现了从ftp服务器上载文件的功能
        {

            FileInfo fileInf = new FileInfo(filename);
            string uri = "ftp://" + ftpServerIP + path + "/" + fileInf.Name;
            if (path == "")
            {
                uri = "ftp://" + ftpServerIP +"//"+ fileInf.Name;
            }
            else if (path.IndexOf("/") == 0)
            {
                uri = "ftp://" + ftpServerIP + "/" + path + "/" + fileInf.Name;
            }
            else if (path.IndexOf("/") != 0)
            {
                string path1 = "";
                if (path.Substring(0, 1) == "/")
                {
                    path1 = path.Substring(1, path.Length - 1);
                    uri = "ftp://" + ftpServerIP + path1 + "/" + fileInf.Name;
                }
             
            }
            // 在一个命令之后被执行
            Connect(uri.Trim());//连接  
            // 默认为true，连接不会被关闭        
            reqFTP.KeepAlive = false;
            // 指定执行什么命令
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            // 上传文件时通知服务器文件的大小
            reqFTP.ContentLength = fileInf.Length;
            // 缓冲大小设置为kb 
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            long FileSize = fileInf.Length;
            // 打开一个文件流(System.IO.FileStream) 去读上传的文件
            FileStream fs = fileInf.OpenRead();
            try
            {
                // 把上传的文件写入流
                Stream strm = reqFTP.GetRequestStream();
                // 流内容没有结束
                long BytesTotal = 0;
                int state = 0;
                while (true)
                {
                    // 每次读文件流的kb 
                    int contentLen = fs.Read(buff, 0, buffLength);
                    // 把内容从file stream 写入upload stream 
                    if (contentLen == 0)
                    {
                        break;
                    }
                    strm.Write(buff, 0, contentLen);
                    BytesTotal += contentLen;
                    int perc = (int)(((BytesTotal) * 100) / FileSize);
                    if (state != perc)
                    {
                        setProgressBar(progress, perc);
                        state = perc;
                    }
                }
                // 关闭两个流
                strm.Close();
                fs.Close();
            }

            catch (Exception ex)
            {
                fs.Close();
                errormessage = ex.Message;
                // MessageBox.Show(ex.Message, "Upload Error");
            }

        }
        public void setProgressBar(string progress, int perc)
        {
            string str = "<script > setProgress('" + progress + "',  " + perc + ");</script>";
            _context.Response.WriteAsync(str);
            _context.Response.Clear();
        }


        public bool Download(string filePath, string fileName, string progress)////上面的代码实现了从ftp服务器下载文件的功能
        {
            errormessage = "";
            try
            {
                String onlyFileName = Path.GetFileName(fileName);
                string newFileName = Path.Combine(filePath, onlyFileName);

                if (File.Exists(newFileName))
                {
                    errormessage = string.Format("本地文件{0}已存在,无法下载", newFileName);
                    return false;
                }
                string url = "ftp://" + ftpServerIP + "/" + fileName;
                long FileSize = GetFileSize(fileName);
                Connect(url);//连接  
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];
                FileStream outputStream = new FileStream(newFileName, FileMode.Create);
                int state = 0;
                long BytesTotal = 0;
                while (true)
                {
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                    outputStream.Write(buffer, 0, readCount);
                    if (readCount <= 0)
                    {
                        break;
                    }
                    BytesTotal += readCount;
                    int perc = (int)(((BytesTotal) * 100) / FileSize);
                    if (state != perc)
                    {
                        setProgressBar(progress, perc);
                        state = perc;
                    }
                }
                ftpStream.Close();
                outputStream.Close();
                response.Close();
                errormessage = "";
                return true;
            }
            catch (Exception ex)
            {
                errormessage = ex.Message;
                return false;
            }
        }

        //删除文件

        public bool DeleteFileName(string fileName)
        {
            try
            {
                string uri = "ftp://" + ftpServerIP + fileName;
                Connect(uri);//连接          
                // 默认为true，连接不会被关闭
                // 在一个命令之后被执行
                reqFTP.KeepAlive = false;
                // 指定执行什么命令

                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                response.Close();
                return true;
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "删除错误");
                errormessage = ex.Message;
                return false;
            }

        }

        //创建目录
        public bool MakeDir(string dirName)
        {
            try
            {
                string uri = "ftp://" + ftpServerIP + dirName;
                Connect(uri);//连接  
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

                    response.Close();
                
                 return true;
            }
            catch (Exception ex)
            {
                // MessageBox.Show(ex.Message);
                errormessage = ex.Message;
                
                return false;
            }
        }

        //删除目录
        public bool delDir(string dirName)
        {
            try
            {
                string uri = "ftp://" + ftpServerIP + dirName;
                Connect(uri);//连接       
                reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                response.Close();
                return true;
            }

            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
                errormessage = ex.Message;
                return false;
            }
        }

        //获得文件大小

        public long GetFileSize(string filename)
        {
            long fileSize = 0;
            try
            {
                string uri = "ftp://" + ftpServerIP + filename;
                Connect(uri);//连接       
                reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                fileSize = response.ContentLength;
                response.Close();
            }
            catch (Exception ex)
            {
                errormessage = ex.Message;
                //MessageBox.Show(ex.Message);
            }
            return fileSize;
        }

        //文件改名

        public bool Rename(string currentFilename, string newFilename)
        {
            try
            {
                string uri = "ftp://" + ftpServerIP + currentFilename;
                Connect(uri);//连接
                reqFTP.Method = WebRequestMethods.Ftp.Rename;
                reqFTP.RenameTo = newFilename;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                //Stream ftpStream = response.GetResponseStream();
                //ftpStream.Close();
                response.Close();
                return true;
            }
            catch (Exception ex)
            {
                errormessage = ex.Message;
                // MessageBox.Show(ex.Message);
                return false;
            }

        }

        //获得文件明晰
        public string[] GetFilesDetailList()
        {
            return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectoryDetails);
        }

        //获得文件明晰
        public string[] GetFilesDetailList(string path)
        {
            return GetFileList("ftp://" + ftpServerIP + path, WebRequestMethods.Ftp.ListDirectoryDetails);

        }
    }
}
